package com.lemon.smartsafetynew.ui.fragment.ledger;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.fragment.base.BaseTopBtnPullToRefreshFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.contact.DepartmentResult;
import com.lemon.smartsafetynew.entity.contact.DepartmentVo;
import com.lemon.smartsafetynew.entity.event.common.DateEvent;
import com.lemon.smartsafetynew.entity.ledger.LedgerPatrolPersonnelStatisticsVo;
import com.lemon.smartsafetynew.net.services.SafeLedgerServices;
import com.lemon.smartsafetynew.ui.activity.ledger.LedgerPatrolPersonnelDetailActivity;
import com.lemon.smartsafetynew.ui.activity.ledger.LedgerPatrolStatisticsActivity;
import com.lemon.smartsafetynew.ui.adapter.ledger.LedgerPersonnelStatisticsAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import kale.adapter.LemonRcvAdapter;
import okhttp3.Call;

/**
 * Created by Andrew on 2017/9/14.
 */

public class LedgerPatrolPersonnelStatisticsFragment
        extends BaseTopBtnPullToRefreshFragment<LedgerPatrolPersonnelStatisticsVo, List<LedgerPatrolPersonnelStatisticsVo>>
        implements RecyclerTClickListener<LedgerPatrolPersonnelStatisticsVo> {

    private String[] labels = new String[]{
            "姓名", "完成任务", "异常任务"
    };

    private List<String> mDepartmentSpanner = new ArrayList<>();
    private List<DepartmentVo> mDepartmentVoList;
    private static String departmentId = "";

    public static LedgerPatrolPersonnelStatisticsFragment newInstance() {

        Bundle args = new Bundle();

        LedgerPatrolPersonnelStatisticsFragment fragment = new LedgerPatrolPersonnelStatisticsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onPullRefresh() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("date", dateTv.getText().toString().trim());
        params.put("company_id", AccountUtil.getCompanyId());
        params.put("dept_id", departmentId);
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        SafeLedgerServices
                .init()
                .getSafePatrolPersonnelStatisticsVo(RefreshType.REFRESH, params);

    }

    @Override
    public void onLoadMore() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("date", dateTv.getText().toString().trim());
        params.put("company_id", AccountUtil.getCompanyId());
        params.put("dept_id", departmentId);
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        SafeLedgerServices
                .init()
                .getSafePatrolPersonnelStatisticsVo(RefreshType.LOAD_MORE, params);
    }

    @Override
    public boolean goRefreshOnCreate() {
        return true;
    }

    @Override
    public LemonRcvAdapter<LedgerPatrolPersonnelStatisticsVo> getLemonAdapter() {
        return new LedgerPersonnelStatisticsAdapter(mDataList, this);
    }

    @Override
    public String getHttpTag() {
        return KeyConstants.URL_GET_SAFE_LEDGER_PATROL_PERSONNEL_STATISTICS;
    }

    @Override
    public void onItemClick(LedgerPatrolPersonnelStatisticsVo data, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_LEDGER_PATROL_PERSONNEL_STATISTICS, data);
        UIHelper.showActivity(getmContext(), bundle, LedgerPatrolPersonnelDetailActivity.class);
    }

    @Override
    protected void initViews() {
        super.initViews();
        getDepartment();
    }

    /**
     * 初始化页面
     */
    private void initLabels() {

        dateTv.setText(CommonUtil.secondToTimeStr(System.currentTimeMillis(), DateTypeEnum.DAY));
        spinnerText.setText(mDepartmentSpanner.get(0));
        listBarLayout.setVisibility(View.VISIBLE);
        spinnerLayout.setVisibility(View.VISIBLE);

        spinnerChooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(spinnerChooseLayout, new PopupListener(), mDepartmentSpanner);
            }
        });

        for (int i = 1; i < listBarLayout.getChildCount(); i++) {
            TextView textView = (TextView) listBarLayout.getChildAt(i);
            textView.setText(labels[i - 1]);
        }

    }

    private class PopupListener implements RecyclerTClickListener<String> {
        @Override
        public void onItemClick(String data, int position) {
            spinnerText.setText(data);
            departmentId = getDepartmentId(data);
            dismissPopWindow();
            doPullRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDateEvent(DateEvent event) {

        if (LedgerPatrolStatisticsActivity.class.getName().equals(event.getTag())) {
            dateTv.setText(CommonUtil.avoidNullString(event.getDate()));
            doPullRefresh();
        }
    }


    /**
     * 从服务器获取部门列表
     */
    private void getDepartment() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_id", AccountUtil.getCompanyId());


        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(IApplication.context());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.GET_ALL_DEPARTMENT);

        OkHttpUtils.post()
                .url(serverUrl)
                .params(params)
                .build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e) {
                mHUDUtil.showErrorTip("出错了", new HUDUtil.CallBack() {
                    @Override
                    public void onCall() {

                    }
                });
            }

            @Override
            public void onResponse(String response) {

                Log.e("返回onResponse", response);

                Gson gson = new Gson();
                DepartmentResult result = gson.fromJson(response, DepartmentResult.class);

                if(result == null || result.getResult() == null) {
                    mHUDUtil.showErrorTip("出错了");
                    return;
                }

                if (result.isError()) {

                    mHUDUtil.showErrorTip(result.getError().getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });

                } else {

                    mDepartmentVoList = result.getResult();
                    mDepartmentSpanner.clear();  //清空
                    for (DepartmentVo departmentVo : mDepartmentVoList) { //装填
                        mDepartmentSpanner.add(departmentVo.getName());
                    }
                    mDepartmentSpanner.add(0, "全部人员");  //添加第一个为全部人员

                    initLabels();
                }
            }
        });
    }

    /**
     * 获取部门的id信息
     *
     * @param name
     * @return
     */
    private String getDepartmentId(String name) {

        String departmentId = "";

        int index = mDepartmentSpanner.lastIndexOf(name);

        if (index > 0) {
            departmentId = mDepartmentVoList.get(index - 1).getDepartment_id();
            //Log.e("yxy", "mDepartmentVoList.get(index - 1).getDepartment_id() = " + mDepartmentVoList.get(index - 1).getDepartment_id());
            //Log.e("yxy", "mDepartmentVoList.get(index - 1).getName() = " + mDepartmentVoList.get(index - 1).getName());
        }

        return departmentId;
    }
}
